﻿Imports System
Imports System.Runtime.InteropServices

Namespace System.Workflow.Runtime
    Friend MustInherit Class AmbientEnvironment
        Implements IDisposable
        ' Methods
        Protected Sub New(ByVal env As Object)
            If (AmbientEnvironment.threadData Is Nothing) Then
                AmbientEnvironment.threadData = New EnvWrapper
            End If
            AmbientEnvironment.threadData.Push(env, Me._prevEnv, Me._prevRC)
        End Sub

        Friend Shared Function Retrieve() As Object
            If (Not AmbientEnvironment.threadData Is Nothing) Then
                Return AmbientEnvironment.threadData.Retrieve
            End If
            Return Nothing
        End Function

        Private Sub System.IDisposable.Dispose() Implements IDisposable.Dispose
            AmbientEnvironment.threadData.Pop(Me._prevEnv, Me._prevRC)
            If (Me._prevRC = 0) Then
                AmbientEnvironment.threadData = Nothing
            End If
        End Sub


        ' Fields
        Private ReadOnly _prevEnv As Object
        Private ReadOnly _prevRC As Integer
        <ThreadStatic> _
        Private Shared threadData As EnvWrapper

        ' Nested Types
        Private Class EnvWrapper
            ' Methods
            Friend Sub Pop(ByVal prevEnv As Object, ByVal prevRC As Integer)
                Me._rc -= 1
                Me._currEnv = prevEnv
                Dim num1 As Integer = Me._rc
            End Sub

            Friend Sub Push(ByVal env As Object, <Out> ByRef prevEnv As Object, <Out> ByRef prevRc As Integer)
                prevEnv = Me._currEnv
                prevRc = Me._rc
                Me._rc += 1
                Me._currEnv = env
            End Sub

            Friend Function Retrieve() As Object
                Return Me._currEnv
            End Function


            ' Fields
            Private _currEnv As Object
            Private _rc As Integer
        End Class
    End Class
End Namespace

